<template>
  <ele-modal
    :width="950"
    :visible="visible"
    :confirm-loading="loading"
    :title="actionStatus == 'edit' ? '修改用户' : '新建用户'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-row :gutter="24">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input
              allow-clear
              placeholder="请输入姓名"
              v-model:value="form.name"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="年龄">
            <a-input
              allow-clear
              placeholder="请输入年龄"
              v-model:value="form.age"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="性别">
            <a-select
              optionFilterProp="label"
              allow-clear
              v-model:value="form.sex"
              placeholder="请选择性别"
              @change="sexChange"
            >
              <a-select-option value="男">男</a-select-option>
              <a-select-option value="女">女</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="手机号" v-bind="validateInfos.mobile">
            <a-input
              allow-clear
              placeholder="请输入手机号"
              v-model:value="form.mobile"
              autocomplete="off"
              @blur="validate('account', { trigger: 'change' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="出生日期">
            <a-date-picker
              class="ele-fluid"
              valueFormat="YYYY/MM/DD"
              placeholder="请选择出生日期"
              v-model:value="form.birthday_date"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="工号">
            <a-input
              allow-clear
              placeholder="请输入工号"
              v-model:value="form.code"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="在职状态">
            <a-select
              optionFilterProp="label"
              :options="workData"
              allow-clear
              v-model:value="form.work_status"
              placeholder="请选择在职状态"
              @change="workChange"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="入职时间">
            <a-date-picker
              class="ele-fluid"
              valueFormat="YYYY/MM/DD"
              placeholder="请选择入职时间"
              v-model:value="form.employment_date"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="转正时间">
            <a-date-picker
              class="ele-fluid"
              valueFormat="YYYY/MM/DD"
              placeholder="请选择转正时间"
              v-model:value="form.formal_date"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="离职时间">
            <a-date-picker
              class="ele-fluid"
              valueFormat="YYYY/MM/DD"
              placeholder="请选择离职时间"
              v-model:value="form.leave_date"
              autocomplete="off"
            />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="角色" v-bind="validateInfos.main_role">
            <a-select
              optionFilterProp="label"
              :options="roleData"
              allow-clear
              v-model:value="form.main_role"
              placeholder="请选择角色"
              @change="roleChange"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="登录用户名" v-bind="validateInfos.account">
            <a-input
              allow-clear
              placeholder="请输入登录用户名"
              v-model:value="form.account"
              autocomplete="off"
              @blur="validate('account', { trigger: 'change' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="登录密码" v-bind="validateInfos.password">
            <a-input-password
              allow-clear
              placeholder="请输入登录密码"
              v-model:value="form.password"
              autocomplete="new-password"
              @blur="
                validate('password', { trigger: 'change' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="QQ">
            <a-input
              allow-clear
              placeholder="请输入QQ"
              v-model:value="form.qq"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="邮箱">
            <a-input
              allow-clear
              placeholder="请输入邮箱"
              v-model:value="form.email"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="紧急联系人">
            <a-input
              allow-clear
              placeholder="请输入紧急联系人"
              v-model:value="form.contact_name"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item
            label="紧急联系人电话"
            v-bind="validateInfos.contact_mobile"
          >
            <a-input
              allow-clear
              placeholder="请输入紧急联系人电话"
              v-model:value="form.contact_mobile"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="身份证号码">
            <a-input
              allow-clear
              placeholder="请输入身份证号码"
              v-model:value="form.id_card"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="户口所在地" autocomplete="off">
            <a-input
              allow-clear
              placeholder="请输入户口所在地"
              v-model:value="form.residence_address"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="现住址">
            <a-input
              allow-clear
              placeholder="请输入现住址"
              v-model:value="form.live_address"
              autocomplete="off"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Form } from 'ant-design-vue';
  import { uploadUrl } from '@/config/setting';
  import { emailReg, phoneReg, identityReg } from 'ele-admin-pro';
  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { detail } from '@/api/user/store_user';
  import { get_role_select } from '@/api/material/select';

  // 表格列配置
  const useForm = Form.useForm;

  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean,
    // 编辑edit/新建add
    actionStatus: String,
    // 编辑数据id
    editDataId: [String, Number],
    storeId: String
  });

  const emit = defineEmits(['done', 'update:visible']);

  const status = ref(null); //是否启用
  const main_role = ref(null); //主角色
  const other_roles = ref([]); //其他角色
  const work_status = ref(); //工作状态
  onMounted(() => {
    form.store_code = props.storeId;
    form.user_id = props.editDataId;
    if (props.editDataId) {
      detail({ user_id: props.editDataId }).then((res) => {
        //console.log('res:', res);
        form.main_role = null;
        form.other_roles = [];
        /* res.role.forEach((item) => {
	      if (item.is_main == 1) {
	        form.main_role = item.role_id;
	      } else {
	        form.other_roles.push(item.role_id);
	      }
	    }); */
        Object.keys(form).map((key) => {
          if (res.info) {
            form[key] =
              res && res[key]
                ? String(res[key])
                : res.info[key]
                ? String(res.info[key])
                : null;
            if (key.indexOf('_date') >= 0) {
              form[key] = res.info[key];
            }
          }
          imageUrl.value = res.avatar_path;
          /* if (key === 'main_role' || key === 'other_roles') {
            let arr = [];
            res.roles.map((roleItem) => {
              if (roleItem.pivot.is_main === 1) {
                form[key] = String(roleItem.id);
              } else {
                arr.push(String(roleItem.id));
                form.other_roles = arr;
              }
            });
          } */
        });
        form.status = res.status == 1 ? '是' : '否';
        if (res.role.length > 0) {
          form.main_role = res.role[0].role_id.toString();
        }
        console.log('from===', form);
      });
    }
  });

  const imageUrl = ref('');
  // 头像上传
  const images = ref([]);
  /* 完全自己控制选择文件后的处理 */
  const uploadHandler = (info) => {
    if (info && info.file && info.file.response) {
      const data = info.file.response.data;
      imageUrl.value = data.path;
      form.avatar = data.id;
    }
  };

  /* 更新性别选中数据 */
  const sexChange = (value) => {
    console.log('性别', value);
    form.sex = value;
  };

  // 是否启用
  const statusData = ref([
    { value: '1', label: '是' },
    { value: '0', label: '否' }
  ]);

  /* 更新是否启用数据 */
  const statusChange = (value) => {
    console.log('是否启用', value);
    form.status = value;
  };

  // 主角色选择
  let roleData = ref([]);
  let otherRoleData = ref([]);
  const params = ref({});
  if (props.actionStatus == 'add') {
    params.value.store_code = props.storeId;
  } else {
    params.value.user_id = props.editDataId;
  }
  get_role_select(params.value).then(async (res) => {
    roleData.value = await res.map((d) => {
      return {
        value: d.id.toString(),
        label: d.name
      };
    });
    otherRoleData.value = await res.map((d) => {
      return {
        value: String(d.id),
        label: d.name
      };
    });
  });

  /* 更新主角色选择数据 */
  const roleChange = (value) => {
    form.main_role = String(value);
  };

  /* 更新其他角色选择数据 */
  const otherRoleChange = (value) => {
    console.log(value);
    form.other_roles = value;
  };

  // 工作状态
  const workData = ref([
    { value: '0', label: '试用' },
    { value: '1', label: '正式' },
    { value: '2', label: '离职' }
  ]);

  /* 更新工作状态数据 */
  const workChange = (value) => {
    console.log('工作状态', value);
    form.work_status = value;
  };

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const form = reactive({
    user_id: '',
    name: '',
    account: '',
    password: '',
    store_code: '',
    status: '',
    main_role: null,
    code: '',
    age: '',
    sex: null,
    birthday_date: '',
    employment_date: '',
    formal_date: '',
    leave_date: '',
    work_status: null,
    mobile: '',
    qq: '',
    email: '',
    contact_name: '',
    contact_mobile: '',
    id_card: '',
    residence_address: '',
    live_address: ''
  });
  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入用户名',
        type: 'string',
        trigger: 'blur'
      }
    ],
    mobile: [
      {
        required: true,
        message: '请输入手机号',
        type: 'string',
        trigger: 'blur'
      }
    ],
    main_role: [
      {
        required: true,
        message: '请选择角色',
        type: 'string',
        trigger: 'blur'
      }
    ],
    account: [
      {
        required: true,
        message: '请输入登录用户名',
        type: 'string',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        message: '请输入登录密码',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const { validate, validateInfos } = useForm(form, rules);
  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        if (form.status.indexOf('是') >= 0 || form.status.indexOf('否') >= 0) {
          form.status = form.status == '是' ? '1' : '0';
        }
        emit('done', form);
      })
      .catch(() => {});
  };
  /* 更新visible */
  const updateVisible = (value) => {
    emit('update:visible', value);
  };
</script>
<style scoped></style>
